package com.zhsm.fuxi.utils

import android.content.DialogInterface
import com.hankkin.reading.control.UserControl
import com.hankkin.reading.http.HttpClientUtils
import com.qiniu.android.common.FixedZone
import com.qiniu.android.storage.*
import com.zhsm.paipaiout.baselibrary.utils.LoadingUtils
import com.zhsm.paipaiout.baselibrary.utils.LogUtils
import com.zhsm.paipaiout.baselibrary.utils.ToastUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers


/**
 * Created by GuZhC on 2018/10/31.
 * describe:七牛上传图片工具类
 */
class QiniuUpLoadHelper constructor(category: Int) {

    var category: Int = category
    var filePath: String? = null
    private var isCancel = false
    private var isBegin = false

    val uploadManager: UploadManager by lazy {
        val config = Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .zone(FixedZone.zone0)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build()
        UploadManager(config)
    }

    //获取token 后调用七牛上传
    fun uploadPic() {
        isBegin = false
        val map = HashMap<String, Any>()
        map["customerId"] = UserControl.getId()
        map["category"] = category
        HttpClientUtils.Builder.getPaipiaHttp().getQiniuToken(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    //编写订阅触发时的公共代码
                    if (it.code != 1000) {
                        if (!it.msg.isNullOrEmpty()) {
                            upLoadPicListener?.onError(it.msg)
                        }
                        upLoadPicListener?.onError("上传图片失败")
                    } else {
                        it.data?.let {
                            it.key?.let { it1 -> it.token?.let { it2 -> uploadPicTrue(it1, it2) } }
                        }
                    }

                }, {
                    //编写订阅失败的公共代码
                    upLoadPicListener?.onError("无法连接服务器")
                }, {
                    //编写订阅完成后的公共代码
                })
    }

    /**
     * 可以显示进度还可以停止上传图片的方法
     * @param filePath
     * @param picName
     * @param token
     */
    fun uploadPicTrue(picName: String, token: String) {
        if (filePath.isNullOrEmpty())ToastUtils.makeText("未设置图片路径")
        LoadingUtils.onhideLoading(DialogInterface.OnDismissListener {
            if(isBegin) setCancle(true)
//            LogUtils.e("qiniu", "up cancel")
        })
        isBegin =true
        uploadManager.put(filePath, picName, token, { key, info, res ->
                    //res包含hash、key等信息，具体字段取决于上传策略的设置
                    if (info.isOK) {
//                        Logger.i("qiniu", "Upload Success")
                        isBegin =false
                        upLoadPicListener?.onSuccess(key)
                    } else {
                        //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        isBegin =false
                        upLoadPicListener?.onError(info.error)
                    }
//                    Log.i("qiniu", "$key,\r\n $info,\r\n $res")
                }, UploadOptions(null, null, false,
                UpProgressHandler { key, percent -> LogUtils.e("qiniu", "$key: $percent") },
                UpCancellationSignal { isCancel }))
    }

    /**
     *
     * @param value 设置是否停止图片上传
     */
    fun setCancle(value: Boolean) {
        isCancel = value
    }



    private var upLoadPicListener: UpLoadPicListener? = null

    interface UpLoadPicListener {
        fun onSuccess(key: String)
        fun onError(msg: String)
    }

    fun setUpLoadPicListener(mUpLoadPicListener: UpLoadPicListener?) {
        this.upLoadPicListener = mUpLoadPicListener
    }

}